package com.ruangong.GitClient.app.Navigation;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import com.ruangong.GitClient.GitConfig;
import com.ruangong.GitClient.GiteeAPI.GiteeUser;
import com.ruangong.GitClient.R;
import com.ruangong.GitClient.app.GitHubFile.FileViewerActivity;
import com.ruangong.GitClient.app.GiteeFile.GiteeViewerActivity;
import com.ruangong.GitClient.app.HunhepanMenu;
import com.ruangong.GitClient.app.Password.PasswordActivity;
import com.ruangong.GitClient.app.TravelExpense.TravelEventsListActivity;
import com.ruangong.GitClient.app.YanZhaoWang.YanZhaoWangMenu;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.nio.charset.StandardCharsets;


public class MenuActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        ImageButton buttonFunction1 = findViewById(R.id.buttonFunction1);
        ImageButton buttonFunction2 = findViewById(R.id.buttonFunction2);
        ImageButton buttonFunction3 = findViewById(R.id.buttonFunction3);
        ImageButton buttonFunction4 = findViewById(R.id.buttonFunction4);
        ImageButton buttonFunction5 = findViewById(R.id.buttonFunction5);
        ImageButton buttonFunction6 = findViewById(R.id.buttonFunction6);
        ImageButton buttonFunction7 = findViewById(R.id.buttonFunction7);
        buttonFunction1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击按钮1的逻辑
                startActivity(new Intent(MenuActivity.this, PasswordActivity.class));
            }
        });

        buttonFunction2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击按钮2的逻辑
                startActivity(new Intent(MenuActivity.this, HunhepanMenu.class));
            }
        });

        buttonFunction3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击按钮3的逻辑
                startActivity(new Intent(MenuActivity.this, TravelEventsListActivity.class));
            }
        });
        // 添加更多按钮的点击事件处理
        buttonFunction4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击按钮4的逻辑
                startActivity(new Intent(MenuActivity.this, YanZhaoWangMenu.class));
            }
        });

        buttonFunction5.setOnClickListener((view -> {
            initiateGithubOAuth();
        }));

        buttonFunction6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击按钮6的逻辑
                startActivity(new Intent(MenuActivity.this, GiteeViewerActivity.class));
            }
        });

        buttonFunction7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理点击按钮7的逻辑
                startActivity(new Intent(MenuActivity.this, FileViewerActivity.class));
            }
        });
    }

    //GitHub OAuth
    private void initiateGithubOAuth() {
        String clientId = "Ov23liOzEWkP4TbHemiZ";
        String redirectUri = "myapp://oauth";  // 确保这与GitHub应用设置中的重定向URI匹配
//        String scope = "repo,user";  // 请求适当的权限
        String scope = "repo,admin:org,admin:public_key,admin:repo_hook,admin:org_hook,gist,notifications,user,delete_repo,write:discussion";  // 请求适当的权限

        Uri uri = Uri.parse("https://github.com/login/oauth/authorize")
                .buildUpon()
                .appendQueryParameter("client_id", clientId)
                .appendQueryParameter("redirect_uri", redirectUri)
                .appendQueryParameter("scope", scope)
                .appendQueryParameter("response_type", "code")
                .build();

        Log.d("MenuActivity", "OAuth URL: " + uri.toString());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    private void fetchAccessTokenFromGitHub(String code) {
        // 这里应实现获取访问令牌的具体逻辑
        Log.d("MenuActivity", "Authorization code received: " + code);
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
//                .add("client_id", "Ov23liOzEWkP4TbHemiZ")
//                .add("client_secret", "72b2540eda81bc2b6c3e288c2d92ba18023a7f2f")
//                .add("code", code)
//                .add("redirect_uri", "myapp://oauth")
//                .add("grant_type", "authorization_code")
                .add("client_id", GitConfig.GITHUB_CLIENT_ID)
                .add("client_secret", GitConfig.GITHUB_CLIENT_SECRET)
                .add("code", code)
                .add("redirect_uri", GitConfig.GITHUB_REDIRECT_URI)
                .add("grant_type", GitConfig.GRANT_TYPE)
                .build();

        Request request = new Request.Builder()
                .url("https://github.com/login/oauth/access_token")
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 解析响应体，提取访问令牌
                    String responseData = response.body().string();
                    Log.d("OAuth", "Access Token: " + responseData);
                    //TODO 这里会获取到GitHub的访问令牌 Token 用于构建GitHubUser对象，就可以存下来这个Token来查看账户自带仓库的内容了。想办法给它存起来。
                    String accessToken = extractAccessToken(responseData);
                    if (accessToken != null) {
                        try {
                            testGitHubApi(accessToken);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        Log.e("OAuth", "Access token not found in the response");
                    }
                } else {
                    Log.e("OAuth", "Failed to fetch access token");
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("OAuth", "Request failed", e);
            }
        });
    }

    public void testGitHubApi(String accessToken) throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.github.com/repos/SilverXQI/Silver/contents/")
//                .url("https://api.github.com/user")
                .header("Authorization", "token " + accessToken)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    // 处理成功的响应
                    String responseData = response.body().string();
                    Log.d("API Test", "Response data: " + responseData);
//                    Type listType2 = new TypeToken<List<GitHubFile>>() {
//                    }.getType();
//                    List<GitHubFile> files = new Gson().fromJson(responseData, listType2);
                } else {
                    // 打印错误响应
                    Log.e("API Test", "Failed to fetch data: " + response.message());
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                // 处理请求失败的情况
                Log.e("API Test", "Request failed: " + e.getMessage());
            }
        });
    }

    private String extractAccessToken(String response) throws IOException {
        Uri uri = Uri.parse("dummy://dummy?" + response);
        return uri.getQueryParameter("access_token");
//        try {
//            JSONObject jsonObject = new JSONObject(json);
//            return jsonObject.getString("access_token");
//        } catch (JSONException e) {
//            throw new IOException("Failed to parse access token", e);
//        }
    }





    // 接收 Gitee 回调的逻辑，可根据需要添加到适当位置
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Uri uri = intent.getData();
        if (uri != null) {
            // 检查是不是GitHub的回调
            if ("myapp".equals(uri.getScheme()) && "oauth".equals(uri.getHost())) {
                String code = uri.getQueryParameter("code");
                if (code != null) {
                    fetchAccessTokenFromGitHub(code);
                }
            }
            // 检查是不是Gitee的回调
            else if ("myapp".equals(uri.getScheme()) && "callback".equals(uri.getHost())) {
                String code = uri.getQueryParameter("code");
                if (code != null) {
                    fetchAccessTokenFromGitee(code);
                }
            }
        }
    }
    private void fetchAccessTokenFromGitee(String code) {
        // 省略了具体实现，你可以参照先前的示例来编写这部分代码
        Log.d("OAuthCallback", "Received code: " + code);
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
//                .add("grant_type", "authorization_code")
//                .add("code", code)
//                .add("client_id", "8d2ed355a3b431c98f9302ef20df0558f27616c8f3135bca58824d4f835ade43")
//                .add("client_secret", "4a599f30d6bc679fbe0388398bd18b6a23e272c6c8d05c8b51cc042e2d2c1881")
//                .add("redirect_uri", "myapp://callback")
                .add("grant_type", GitConfig.GRANT_TYPE)
                .add("code", code)
                .add("client_id", GitConfig.GITEE_CLIENT_ID)
                .add("client_secret", GitConfig.GITEE_CLIENT_SECRET)
                .add("redirect_uri", GitConfig.GITEE_REDIRECT_URI)
                .build();

        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token")
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();

                    // 获取 Shared Preferences 对象
                   // SharedPreferences sharedPreferences = getSharedPreferences("app_data", Context.MODE_PRIVATE);
                   // SharedPreferences.Editor editor = sharedPreferences.edit();

                    // 将 JSON 字符串存储到 Shared Preferences 中
                    //editor.putString("json_data", responseBody);
                   // editor.apply();



                    Log.d("Token", "Access token: " + responseBody);
                    //TODO: 这里会获取到Gitee的访问令牌 Token 用于构建GiteeUser对象，就可以存下来这个Token来查看账户自带仓库的内容了。想办法给它存起来。
                    //TODO：再加一个刷新的按钮，刷新Token，执行GiteUser.refreshToken()就执行这个方法就行
                    GiteeUser giteeUser = new GiteeUser();//构建个通用对象，所有程序运行之前构建（你找个地方放，我不知道放哪）相当于创建个用户，然后用户登陆就把这个用户的Token给存起来。
                    /*
                    {"access_token":"7735112db6b139495f3883030bc1ac98",
                    "token_type":"bearer",
                    "expires_in":86400,
                    "refresh_token":"9649b65faee309bbae1eec463a973a4edfcb25e166ae6a57387cc55130a5b777",
                    "scope":"user_info projects pull_requests issues notes keys hook groups gists enterprises emails",
                    "created_at":1715420217
                    }
                     */
                    GiteeUser.GiteeUserFromJson(responseBody);//这个函数可以修改GiteeUser的静态变量，就说明这个用户的Token已经存起来了。保留在这个位置
                    SharedPreferences sharedPreferences = getSharedPreferences("app_data", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("access_token", giteeUser.getAccessToken());
                    editor.putString("refresh_token", giteeUser.getRefreshToken());
                    editor.apply(); // 提交保存

                    String accessToken = null;
                    try {
                        accessToken = extractToken(responseBody);
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                    testGiteeApi(accessToken);  // Continue to test Gitee API with the token
                } else {
                    Log.e("Token", "Failed to fetch access token");
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("Token", "Error fetching access token", e);
            }
        });
    }
    private String extractToken(String json) throws JSONException {
        // Assuming the response is in JSON format and contains an access_token field
        JSONObject jsonObject = new JSONObject(json);
        return jsonObject.getString("access_token");
    }

    private void testGiteeApi(String accessToken) {
        OkHttpClient client = new OkHttpClient();
        String url = "https://gitee.com/api/v5/repos/SilverXQ/ruan-gong-project/contents/app/src/main/java/com/ruangong/GitClient/YanZhaoWang/YanZhaoWang.java";

        Request request = new Request.Builder()
                .url(url)
                .header("Authorization", "token " + accessToken)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    try {
                        JSONObject jsonObject = new JSONObject(responseBody);
                        String encodedContent = jsonObject.getString("content");
                        String decodedContent = new String(Base64.decode(encodedContent, Base64.DEFAULT), StandardCharsets.UTF_8);
                        Log.d("GiteeAPI", "Decoded File Content: " + decodedContent);
                        // 这里可以进一步处理解码后的文件内容
                    } catch (JSONException e) {
                        Log.e("GiteeAPI", "JSON parsing error", e);
                    }
                } else {
                    Log.e("GiteeAPI", "Failed to fetch file: " + response.message());
                }
            }

            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("GiteeAPI", "Error fetching file", e);
            }
        });
    }



//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        Uri uri = intent.getData();
//        if (uri != null && uri.getScheme().equals("myapp")) {
//            String code = uri.getQueryParameter("code");
//            if (code != null) {
//                NetworkUtils.fetchAccessToken(code, new Callback() {
//                    @Override
//                    public void onResponse(Call call, Response response) throws IOException {
////                        String responseBody = response.body().string();
//                        // 这里处理获取到的访问令牌
//                        if (response.isSuccessful()) {
//                            // 处理响应体，例如提取和保存令牌
//                            String responseBody = response.body().string();
//                            // 这里可以添加代码来处理获取的访问令牌
//                            Log.d("OAuthRedirectActivity", "Access token: " + responseBody);
//                            Map<String, String> params = new HashMap<>();
//                            String[] pairs = responseBody.split("&");
//                            for (String pair : pairs) {
//                                String[] keyValue = pair.split("=");
//                                if (keyValue.length > 1) {
//                                    params.put(keyValue[0], keyValue[1]);
//                                } else {
//                                    params.put(keyValue[0], ""); // Assume empty string if no value is present
//                                }
//                            }
//
//                            String accessToken = params.get("access_token");
//                            System.out.println("Access token: " + accessToken);
//                            String refreshToken = params.get("refresh_token");
//                            System.out.println("Refresh token: " + refreshToken);
//                            int expiresIn = Integer.parseInt(params.get("expires_in"));
//                            System.out.println("Expires in: " + expiresIn);
//                            int refreshTokenExpiresIn = Integer.parseInt(params.get("refresh_token_expires_in"));
//                            System.out.println("Refresh token expires in: " + refreshTokenExpiresIn);
//
////                            MoMingUtil.fetchPrivateRepos(accessToken);
//                            OkHttpClient client = new OkHttpClient();
//                            Request request = new Request.Builder()
//                                    .url("https://api.github.com/repos/SilverXQI/Silver_Python")
//                                    .header("Authorization", "Bearer " + accessToken)
//                                    .build();
//
//                            client.newCall(request).enqueue(new Callback() {
//                                @Override
//                                public void onResponse(Call call, Response response) throws IOException {
//                                    if (response.isSuccessful()) {
//                                        String responseBody = response.body().string();
//                                        System.out.println("Private Repos: " + responseBody);
//                                        Log.d("OAuthRedirectActivity", "Private Repos: " + responseBody);
//                                    } else {
//                                        System.out.println("Failed to fetch private repos: " + response.code());
//                                        Log.e("OAuthRedirectActivity", "Failed to fetch private repos: " + response.code());
//                                    }
//                                }
//
//                                @Override
//                                public void onFailure(Call call, IOException e) {
//                                    e.printStackTrace();
//                                }
//                            });
//                        } else {
//                            // 处理错误响应
//                            Log.e("OAuthRedirectActivity", "Failed to fetch access token");
//                        }
//                    }
//
//                    @Override
//                    public void onFailure(Call call, IOException e) {
//                        // 处理错误情况
//                    }
//                });
//            }
//        }
//    }
}

